/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.authority.controller;

import com.wallellen.authority.domain.Organization;
import com.wallellen.authority.domain.Post;
import com.wallellen.authority.domain.User;
import com.wallellen.authority.service.UserServiceInterface;
import com.wallellen.core.page.OperateType;
import com.wallellen.core.page.RequestMode;
import com.wallellen.core.page.ViewMode;
import com.wallellen.core.sql.query.DBRule;
import com.wallellen.core.sql.query.DataQuery;
import com.wallellen.core.sql.result.DataResult;
import com.wallellen.web.WebUtils;
import com.wallellen.web.easy.EasyUiUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by walle on 12/12/15.
 */

@RequestMapping({"/user"})
@Controller
public class WebUserController extends WebUtils {
    private static final Logger log = LoggerFactory.getLogger(WebUserController.class);
    private static final long serialVersionUID = 1L;
    @Resource
    UserServiceInterface userServiceImpl;

    public UserServiceInterface getUserServiceImpl() {
        return this.userServiceImpl;
    }

    public void setUserServiceImpl(UserServiceInterface userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    @RequestMapping({"/query"})
    @ResponseBody
    public Map<String, Object> queryall(@ModelAttribute("query") DataQuery query, HttpServletRequest request, HttpSession session) {
        try {
            query = EasyUiUtils.formatGridQuery(request, query);
            if (query.getQueryRule().size() <= 0) {
                query.addRule(new DBRule("a.STATE", "1", "="));
            }
            DataResult result = this.userServiceImpl.createUserSimpleQuery(query, getCurrentUser(session))
                    .search();
            result.runDictionary("0:禁用,1:可用,2:删除", "STATE");
            result.runDictionary("1:系统用户,2:其他,3:超级用户", "TYPE");
            result.runformatTime("LOGINTIME", "yyyy-MM-dd HH:mm:ss");
            return ViewMode.getInstance()
                    .putAttrs(EasyUiUtils.formatGridData(result))
                    .returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/list"})
    public ModelAndView index(HttpSession session) {
        return ViewMode.getInstance()
                .returnModelAndView("authority/UserResult");
    }

    @RequestMapping({"/updatePassword"})
    public ModelAndView forSend(HttpSession session) {
        return ViewMode.getInstance()
                .returnModelAndView("frame/password");
    }

    @RequestMapping({"LoginUser_PassWordUpdata"})
    @ResponseBody
    public Object editPassword(HttpSession session, String passwordl, String passwordn1) {
        try {
            if (!this.userServiceImpl.editLoginPassword(getCurrentUser(session).getLoginName(),
                    passwordl, passwordn1)) {
                throw new RuntimeException("密码修改失败！");
            }
            return ViewMode.getInstance()
                    .returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance()
                    .setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/organization"})
    public ModelAndView userOrgTree(HttpSession session, String ids) {
        return ViewMode.getInstance()
                .putAttr("ids", ids)
                .returnModelAndView("authority/UserorgChooseTreeWin");
    }

    @RequestMapping({"/orgUserQuery"})
    @ResponseBody
    public Map<String, Object> queryOrgUser(@ModelAttribute("query") DataQuery query, HttpServletRequest request, String ids) {
        try {
            query = EasyUiUtils.formatGridQuery(request, query);
            query.addRule(new DBRule("ORG.ID", ids, "="));
            DataResult result = this.userServiceImpl.createUserPostQuery(query).search();
            result.runDictionary("0:禁用,1:可用,2:删除", "USERSTATE");
            result.runDictionary("1:标准岗位,2:临时岗位", "TYPE");
            result.runDictionary("0:禁用,1:可用,2:删除", "a.STATE");
            result.runformatTime("LOGINTIME", "yyyy-MM-dd HH:mm:ss");
            return ViewMode.getInstance()
                    .putAttrs(EasyUiUtils.formatGridData(result))
                    .returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/add"})
    @ResponseBody
    public Map<String, Object> addSubmit(User user, HttpSession session, String orgId, String postIds) {
        try {
            User entity = this.userServiceImpl.insertUserEntity(user,
                    getCurrentUser(session), orgId, postIds);
            return ViewMode.getInstance().setOperate(OperateType.ADD)
                    .putAttr("entity", entity).returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setOperate(OperateType.ADD)
                    .setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/edit"})
    @ResponseBody
    public Map<String, Object> editSubmit(User user, HttpSession session, String orgId, String postIds) {
        try {
            User entity = this.userServiceImpl.editUserEntity(user,
                    getCurrentUser(session), orgId, postIds);
            return ViewMode.getInstance().setOperate(OperateType.ADD)
                    .putAttr("entity", entity).returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setOperate(OperateType.ADD)
                    .setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/del"})
    @ResponseBody
    public ModelAndView delSubmit(String ids, HttpSession session) {
        try {
            this.userServiceImpl.deleteUserEntity(ids,
                    getCurrentUser(session));
            return ViewMode.getInstance()
                    .returnModelAndView("authority/UserResult");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance()
                    .setError(e.getMessage())
                    .returnModelAndView("authority/UserResult");
        }
    }

    @RequestMapping({"/init"})
    @ResponseBody
    public ModelAndView initPassWord(String ids, HttpSession session) {
        try {
            this.userServiceImpl.initDefaultPassWord(ids, getCurrentUser(session));
            return ViewMode.getInstance()
                    .returnModelAndView("authority/UserResult");
        } catch (Exception e) {
        }
        return null;
    }

    @RequestMapping({"/form"})
    public ModelAndView view(RequestMode pageset, String ids) {
        try {
            User entity = null;
            switch (pageset.getOperateType()) {
                case 1:
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .returnModelAndView("authority/UserForm");
                case 0:
                    entity = this.userServiceImpl.getUserEntity(ids);
                    List posts = this.userServiceImpl.getUserPosts(ids);
                    Organization organization = this.userServiceImpl
                            .getUserOrganization(ids);
                    return ViewMode.getInstance().putAttr("entity", entity)
                            .putAttr("posts", posts).putAttr("pageset", pageset)
                            .putAttr("organization", organization)
                            .returnModelAndView("authority/UserForm");
                case 2:
                    entity = this.userServiceImpl.getUserEntity(ids);
                    Organization org = this.userServiceImpl.getOrg(entity.getId());
                    List postList = this.userServiceImpl.getPost(entity.getId());
                    String postIds = "";
                    for (int i = 0; i < postList.size(); i++) {
                        postIds = postIds + ((Post) postList.get(i)).getId();
                        if (i < postList.size() - 1) {
                            postIds = postIds + ",";
                        }
                    }
                    return ViewMode.getInstance()
                            .putAttr("pageset", pageset)
                            .putAttr("entity", entity)
                            .putAttr("orgId", org == null ? null : org.getId())
                            .putAttr("postIds", postIds)
                            .returnModelAndView("authority/UserForm");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e + e.getMessage())
                    .returnModelAndView("authority/UserForm");
        }
        return ViewMode.getInstance().returnModelAndView("authority/UserForm");
    }
}